<template>
  <div class="my-posts-page p-4">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <h5>我的发帖</h5>
        </div>
      </template>
      <el-table :data="currentUserPosts" style="width: 100%" v-loading="loading" empty-text="您还没有发布过任何帖子">
        <el-table-column label="帖子标题">
          <template #default="scope">
            <span @click="openDetailModal(scope.row.forumPost)" class="post-title-link">
              {{ scope.row.forumPost.title }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="forumPost.createTime" label="发布时间" width="180">
          <template #default="scope">
            {{ formatTime(scope.row.forumPost.createTime) }}
          </template>
        </el-table-column>

        <el-table-column prop="forumPost.updateTime" label="最后更新" width="180">
          <template #default="scope">
            <span v-if="scope.row.forumPost.updateTime">
              {{ formatTime(scope.row.forumPost.updateTime) }}
            </span>
            <el-tag v-else type="info" size="small">未修改</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="replyList" label="回复数" width="100">
          <template #default="scope">
            {{ scope.row.replyList.length }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button size="small" type="primary" @click="openEditModal(scope.row.forumPost)">管理</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <EditPostModal v-model="editModalVisible" :post="selectedPost" @post-updated="fetchMyPosts"
      @post-deleted="fetchMyPosts" />
    <PostDetailModal v-model="postDetailModalVisible" :post="currentThread" :current-user-id="userStore.user?.id" />
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue';
import { useForumStore } from '@/stores/forum.js';
import { storeToRefs } from 'pinia';
import EditPostModal from '@/components/alert/community/EditPostModal.vue';
import dayjs from 'dayjs';
import PostDetailModal from '@/components/alert/community/PostDetailModal.vue';
import { useUserStore } from '@/stores/user.js';
import webSocketService from '@/util/webSocketService.js';
const forumStore = useForumStore();
const { currentUserPosts, loading, currentThread } = storeToRefs(forumStore);
const userStore = useUserStore();

const postDetailModalVisible = ref(false);
const editModalVisible = ref(false);
const selectedPost = ref(null);

const fetchMyPosts = () => {
  forumStore.fetchCurrentUserPosts({ pageSize: -1 }); // pageSize: -1 获取全部
};

const openEditModal = (post) => {
  selectedPost.value = post;
  editModalVisible.value = true;
};
const openDetailModal = (post) => {
  // 定义获取数据成功后的回调
  const onFetchSuccess = () => {
    forumStore.subscribeToTopic(post.id); // 新增：订阅当前帖子的主题
    postDetailModalVisible.value = true;
  };
  // 调用 store 中的 action 获取完整的帖子数据（包括回复）
  forumStore.fetchPostThread(post.id, onFetchSuccess);
};
const handleNewReply = (replyData) => {
  // 确保当前正在查看帖子，且收到的回复属于当前帖子
  if (!currentThread.value || currentThread.value.forumPost.id !== replyData.postId) {
    return;
  }

  // 确保 replyList 存在
  if (!currentThread.value.replyList) {
    currentThread.value.replyList = [];
  }

  // 检查评论是否已存在，防止重复添加
  const isExist = currentThread.value.replyList.some(r => r.id === replyData.replyId);
  if (!isExist) {
    console.log('实时更新评论:', replyData);
    // 将后端返回的 replyData 构造成前端需要的格式
    const newReply = {
      id: replyData.replyId,
      postId: replyData.postId,
      fromReply: replyData.fatherId || null,
      authorId: replyData.authorId,
      content: replyData.content,
      isTutorReply: replyData.isTutorReply,
      isBest: replyData.isBest,
      createTime: new Date().toISOString(), // 使用客户端时间或后端提供的时间
      isDelete: 0
    };
    currentThread.value.replyList.push(newReply);
  }
};
watch(postDetailModalVisible, (isVisible) => {
  if (!isVisible && currentThread.value && currentThread.value.forumPost) {
    // 弹窗关闭时，取消订阅当前帖子的主题
    forumStore.unsubscribeFromTopic(currentThread.value.forumPost.id);
  }
});
const formatTime = (timeStr) => {
  if (!timeStr) return 'N/A';
  return dayjs(timeStr).format('YYYY-MM-DD HH:mm');
};

onMounted(() => {
  fetchMyPosts();

  // 新增：连接 WebSocket 并注册处理器
  webSocketService.connect();
  webSocketService.on('reply', handleNewReply);
  webSocketService.on('reply_of_reply', handleNewReply);
  webSocketService.on('reply_replied', handleNewReply);
  webSocketService.on('post_replied', handleNewReply);
});
onUnmounted(() => {
  // 组件卸载时，注销处理器并断开连接
  webSocketService.off('reply', handleNewReply);
  webSocketService.off('reply_of_reply', handleNewReply);
  webSocketService.off('reply_replied', handleNewReply);
  webSocketService.off('post_replied', handleNewReply);

  // 如果离开页面时详情弹窗是打开的，需要取消对该帖子的订阅
  if (currentThread.value && currentThread.value.forumPost && postDetailModalVisible.value) {
    forumStore.unsubscribeFromTopic(currentThread.value.forumPost.id);
  }

  webSocketService.disconnect();
});
</script>

<style scoped>
.post-title-link {
  color: #409eff;
  /* Element Plus 默认的链接颜色 */
  cursor: pointer;
  transition: color 0.2s;
}

.post-title-link:hover {
  color: #79bbff;
  /* 鼠标悬浮时的颜色 */
}

.my-posts-page {
  background-color: #f8f9fa;
  min-height: 100vh;
}
</style>